package edu.zhangxu.servlet;

import edu.zhangxu.pojo.Problem;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ProblemIntro extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String user = "root";
        String password = "zxdewecode9182";
        // 加入 ?useUnicode=true&characterEncoding=utf-8 解决查询条件包含中文时查找不到的问题。
        String url = "jdbc:mysql://42.192.125.229:3306/wecode?useUnicode=true&characterEncoding=utf-8";
        String sql = "SELECT id,name,difficulty,submit_count,ac_count FROM problems WHERE name=?";

        resp.setContentType("text/html;charset=utf-8");
        resp.setHeader("Access-Control-Allow-Origin", "*"); // 允许跨域访问
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, user, password);
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, name);
            ResultSet rs = ps.executeQuery();
            Problem p = null;
            if(rs.next()) {
                // 计算通过率
                int submitCount = rs.getInt("submit_count");
                int acCount = rs.getInt("ac_count");
                double acRate = 5.9;
                if(submitCount!=0) {
                    acRate = (double)acCount/submitCount;
                }
//                p = new Problem(rs.getInt("id"), rs.getString("name"),
//                        rs.getString("difficulty"), acRate);
            }
            rs.close();
            ps.close();
            con.close();
            JSONObject jo = JSONObject.fromObject(p);
            resp.getWriter().print(jo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
